package com.example.demo.controller;

import com.example.demo.common.BaseResponse;
import com.example.demo.common.ResultUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统健康检查控制器
 * 无需数据库和区块链即可访问
 *
 * @author Atanycosts
 */
@RestController
@RequestMapping("/system")
@Tag(name = "系统管理", description = "系统健康检查和状态查询")
public class SystemController {

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${feature.database.enabled:false}")
    private boolean databaseEnabled;

    @Value("${feature.blockchain.enabled:false}")
    private boolean blockchainEnabled;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "检查系统是否正常运行")
    public BaseResponse<HealthInfo> health() {
        HealthInfo info = new HealthInfo();
        info.setStatus("UP");
        info.setTimestamp(LocalDateTime.now());
        info.setApplication(applicationName);
        return ResultUtils.success(info);
    }

    /**
     * 功能状态检查
     */
    @GetMapping("/features")
    @Operation(summary = "功能状态", description = "查看各功能模块启用状态")
    public BaseResponse<Map<String, Object>> features() {
        Map<String, Object> features = new HashMap<>();
        features.put("database", databaseEnabled);
        features.put("blockchain", blockchainEnabled);

        // 检查实际 Bean 是否已注册
        Map<String, Object> beanStatus = new HashMap<>();
        beanStatus.put("DataSource", applicationContext.containsBean("dataSource"));
        beanStatus.put("EntityManagerFactory", applicationContext.containsBean("entityManagerFactory"));
        beanStatus.put("BcosSDK", applicationContext.containsBean("bcosSDK"));
        beanStatus.put("BlockchainClient", applicationContext.containsBean("client"));

        features.put("beansRegistered", beanStatus);
        return ResultUtils.success(features);
    }

    /**
     * 健康信息
     */
    @Data
    public static class HealthInfo {
        private String status;
        private LocalDateTime timestamp;
        private String application;
    }
}
